from django.views.generic import View
from libs.parser import JsonParser, Argument
from libs.utils import json_response, generate_random_str
from .models import Course, CourseCategory
from django.db.models import Q
import os


class CourseCategoryView(View):
    """课程类别管理"""
    def get(self, request):
        categories = CourseCategory.objects.filter(is_delete=False)
        return json_response([x.to_dict() for x in categories])

    def post(self, request):
        form, error = JsonParser(
            Argument('id', type=int, required=False),
            Argument('name', help='请输入课程大类名称'),
            Argument('school', help='请输入所属学校'),
            Argument('sort_id', type=int, required=False)
        ).parse(request.body)

        if error is None:
            if form.id:
                category = CourseCategory.objects.filter(pk=form.id).first()
                if not category:
                    return json_response(error='课程类别不存在')
                CourseCategory.objects.filter(pk=form.id).update(**form)
            else:
                category = CourseCategory.objects.create(**form)
            return json_response(category.to_dict())
        return json_response(error=error)
    
    def delete(self, request, category_id=None):
        """删除课程类别"""
        try:
            # 确保有category_id
            if not category_id:
                return json_response(error='缺少课程类别ID')
            
            # 查找课程类别
            category = CourseCategory.objects.filter(pk=category_id).first()
            if not category:
                return json_response(error='课程类别不存在')
            
            # 逻辑删除
            category.is_delete = True
            category.save()
            
            return json_response({'success': True})
        except Exception as e:
            return json_response(error=f'删除失败: {str(e)}')


class CourseView(View):
    def get(self, request):
        form, error = JsonParser(
            Argument('name', required=False),
            Argument('category_id', type=int, required=False),
            Argument('year', type=int, required=False),
            Argument('status', required=False),
        ).parse(request.GET)

        queries = Q(is_delete=False)
        if form.name:
            queries &= Q(name__contains=form.name)
        if form.category_id:
            queries &= Q(category_id=form.category_id)
        if form.year:
            queries &= Q(year=form.year)
        if form.status:
            queries &= Q(status=form.status)

        courses = Course.objects.filter(queries)
        return json_response([x.to_dict() for x in courses])
    
    def post(self, request):
        form, error = JsonParser(
            Argument('id', type=int, required=False),
            Argument('category_id', type=int, help='请选择课程类别'),
            Argument('name', help='请输入课程名称'),
            Argument('year', type=int, help='请输入课程年份'),
            Argument('price', type=float, help='请输入课程价格'),
            Argument('description', required=False),
            Argument('start_date', help='请输入开始日期'),
            Argument('end_date', help='请输入结束日期'),
            Argument('status', help='请选择课程状态')
        ).parse(request.body)

        if error is None:
            if not CourseCategory.objects.filter(id=form.category_id, is_delete=False).exists():
                return json_response(error='课程类别不存在')
            
            if form.id:
                course = Course.objects.filter(pk=form.id).first()
                if not course:
                    return json_response(error='课程不存在')
                Course.objects.filter(pk=form.id).update(**form)
            else:
                course = Course.objects.create(**form)
            return json_response(course.to_dict())
        return json_response(error=error)
    
    def delete(self, request, course_id):
        """删除课程"""
        try:
            # 查找课程
            course = Course.objects.filter(pk=course_id).first()
            if not course:
                return json_response(error='课程不存在')
            
            # 逻辑删除
            course.is_delete = True
            course.save()
            
            return json_response({'success': True})
        except Exception as e:
            return json_response(error=f'删除失败: {str(e)}')

